import tkinter as tk
from tkinter import messagebox, simpledialog
import pyperclip
import keyboard
import threading
import json
import os
from pynput.mouse import Button, Controller
import time

class AutoPasteTool:
    def __init__(self, root):
        self.root = root
        self.root.title("F键自动粘贴工具")
        self.root.geometry("500x400")
        self.root.resizable(False, False)
        
        # 设置窗口样式
        self.root.configure(bg="#f0f0f0")
        
        # 存储F1-F10对应的粘贴内容
        self.paste_content = {f"F{i}": "" for i in range(1, 11)}
        
        # 加载保存的配置
        self.load_config()
        
        # 创建界面
        self.create_widgets()
        
        # 启动热键监听线程
        self.running = False
        self.listener_thread = None
        
    def create_widgets(self):
        # 标题标签
        title_label = tk.Label(
            self.root, 
            text="F键自动粘贴工具", 
            font=("Arial", 16, "bold"),
            bg="#f0f0f0",
            fg="#333333"
        )
        title_label.pack(pady=(20, 10))
        
        # 说明标签
        info_label = tk.Label(
            self.root, 
            text="设置F1-F10键对应的粘贴内容，按Ctrl+F1~F10可自动粘贴到鼠标位置", 
            font=("Arial", 10),
            bg="#f0f0f0",
            fg="#666666"
        )
        info_label.pack(pady=5)
        
        # 内容设置框架
        frame = tk.Frame(self.root, bg="#f0f0f0")
        frame.pack(pady=10, fill="both", expand=True, padx=20)
        
        # 创建F1-F10的输入框
        self.entry_widgets = {}
        for i in range(1, 11):
            row = (i-1) // 2
            col = (i-1) % 2
            
            # 创建容器框架，用于统一宽度
            container = tk.Frame(frame, bg="#f0f0f0")
            container.grid(row=row, column=col, padx=5, pady=5, sticky="ew")
            frame.columnconfigure(col, weight=1)
            
            # 按键标签
            key_label = tk.Label(
                container, 
                text=f"F{i}:", 
                width=5, 
                bg="#f0f0f0",
                fg="#333333",
                anchor="w"
            )
            key_label.grid(row=0, column=0, padx=(0, 5), sticky="w")
            
            # 输入框 - 使用固定宽度并设置填充
            entry = tk.Entry(
                container, 
                width=25,  # 使用固定宽度
                font=("Arial", 10),
                bg="white",
                relief=tk.FLAT,
                highlightthickness=1,
                highlightbackground="#cccccc",
                highlightcolor="#6699cc"
            )
            entry.grid(row=0, column=1, sticky="ew")
            entry.insert(0, self.paste_content[f"F{i}"])
            self.entry_widgets[f"F{i}"] = entry
            
            # 设置容器列权重，使输入框填充可用空间
            container.columnconfigure(1, weight=1)
        
        # 控制按钮框架
        btn_frame = tk.Frame(self.root, bg="#f0f0f0")
        btn_frame.pack(pady=15)
        
        # 启动/停止按钮
        self.control_btn = tk.Button(
            btn_frame, 
            text="启动监听", 
            command=self.toggle_listener,
            font=("Arial", 10, "bold"),
            bg="#4CAF50",
            fg="white",
            relief=tk.FLAT,
            padx=15,
            pady=5,
            cursor="hand2"
        )
        self.control_btn.pack(side="left", padx=8)
        
        # 保存配置按钮
        save_btn = tk.Button(
            btn_frame, 
            text="保存配置", 
            command=self.save_config,
            font=("Arial", 10),
            bg="#2196F3",
            fg="white",
            relief=tk.FLAT,
            padx=15,
            pady=5,
            cursor="hand2"
        )
        save_btn.pack(side="left", padx=8)
        
        # 重置按钮
        reset_btn = tk.Button(
            btn_frame, 
            text="重置", 
            command=self.reset_config,
            font=("Arial", 10),
            bg="#f44336",
            fg="white",
            relief=tk.FLAT,
            padx=15,
            pady=5,
            cursor="hand2"
        )
        reset_btn.pack(side="left", padx=8)
        
        # 状态标签
        self.status_label = tk.Label(
            self.root, 
            text="状态: 未启动", 
            fg="#f44336",
            bg="#f0f0f0",
            font=("Arial", 10)
        )
        self.status_label.pack(pady=5)
        
        # 帮助标签
        help_label = tk.Label(
            self.root, 
            text="使用说明: 设置好内容后，点击启动监听，然后按Ctrl+F1~F10自动粘贴",
            font=("Arial", 8), 
            fg="#666666",
            bg="#f0f0f0"
        )
        help_label.pack(pady=5)
    
    def toggle_listener(self):
        if not self.running:
            # 从输入框获取内容
            for key, entry in self.entry_widgets.items():
                self.paste_content[key] = entry.get()
            
            # 启动监听线程
            self.listener_thread = threading.Thread(target=self.start_listening, daemon=True)
            self.listener_thread.start()
            self.control_btn.config(
                text="停止监听",
                bg="#f44336"
            )
            self.status_label.config(
                text="状态: 已启动", 
                fg="#4CAF50"
            )
            self.running = True
        else:
            # 停止监听
            self.running = False
            keyboard.unhook_all()
            self.control_btn.config(
                text="启动监听",
                bg="#4CAF50"
            )
            self.status_label.config(
                text="状态: 未启动", 
                fg="#f44336"
            )
    
    def start_listening(self):
        # 注册组合键热键
        for i in range(1, 11):
            f_key = f"F{i}"
            # 注册Ctrl+F1到Ctrl+F10
            keyboard.add_hotkey(f"ctrl+{f_key.lower()}", lambda k=f_key: self.perform_paste(k))
        
        # 保持线程运行
        while self.running:
            time.sleep(0.1)
    
    def perform_paste(self, f_key):
        # 获取要粘贴的内容
        content = self.paste_content[f_key]
        
        # 将内容复制到剪贴板
        pyperclip.copy(content)
        
        # 模拟粘贴操作
        mouse = Controller()
        
        # 稍微延迟，确保鼠标位置正确
        time.sleep(0.1)
        
        # 点击获取焦点
        mouse.click(Button.left, 1)
        time.sleep(0.1)
        
        # 模拟Ctrl+V粘贴
        keyboard.press('ctrl')
        keyboard.press('v')
        keyboard.release('v')
        keyboard.release('ctrl')
    
    def save_config(self):
        # 从输入框获取内容
        for key, entry in self.entry_widgets.items():
            self.paste_content[key] = entry.get()
        
        # 保存到文件
        try:
            with open("autopaste_config.json", "w", encoding="utf-8") as f:
                json.dump(self.paste_content, f, ensure_ascii=False, indent=2)
            messagebox.showinfo("成功", "配置已保存")
        except Exception as e:
            messagebox.showerror("错误", f"保存配置失败: {e}")
    
    def load_config(self):
        # 从文件加载配置
        if os.path.exists("autopaste_config.json"):
            try:
                with open("autopaste_config.json", "r", encoding="utf-8") as f:
                    config = json.load(f)
                # 只更新存在的F键
                for key in self.paste_content:
                    if key in config:
                        self.paste_content[key] = config[key]
            except Exception as e:
                messagebox.showerror("错误", f"加载配置失败: {e}")
    
    def reset_config(self):
        # 重置为默认值
        if messagebox.askyesno("确认", "确定要重置所有配置吗？"):
            self.paste_content = {f"F{i}": "" for i in range(1, 11)}
            # 更新界面
            for key, entry in self.entry_widgets.items():
                entry.delete(0, tk.END)
                entry.insert(0, self.paste_content[key])
            messagebox.showinfo("成功", "配置已重置")

if __name__ == "__main__":
    root = tk.Tk()
    app = AutoPasteTool(root)
    root.mainloop()


## python autopaste_tool.py